package cn.edu.zjut.mina.service.impl;

import java.net.InetSocketAddress;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.zjut.mina.bean.RoomInfo;
import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.bean.UserSession;
import cn.edu.zjut.mina.interf.IRoomInfo;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.repository.UserInfoRepository;
import cn.edu.zjut.mina.service.INotificationService;
import cn.edu.zjut.mina.service.IUserFindRoomService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
import cn.edu.zjut.mina.util.UserMap;
import cn.edu.zjut.mina.util.UserSessionMap;

@Service("userFindRoomService")
public class UserFindRoomServiceImpl implements IUserFindRoomService{

	/**
	 * 用于存放用户信息的集合
	 */
	private final UserSessionMap userSessionMap = UserSessionMap.getInstance();
	
	/**
	 * 用于存放用户信息的集合
	 */
	private final UserMap userMap = UserMap.getInstance();
	
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	@Qualifier("notificationService")
	@Autowired
	private INotificationService notificationService;

	@Transactional(rollbackFor=Exception.class)

	public JMessageProtocalRes findRoom(StandardFormat inJson, IoSession session) {
		// TODO Auto-generated method stub
		System.out.println("execute --FindRoom()-- method.");
		
//		if(inJson.userId.equals("76000003")){
//			System.out.println("加入房间不返回任何信息");
//			return null;
//		}
		
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		IRoomInfo roomInfo = userSessionMap.get(inJson.roomId);
		if (roomInfo == null) {
			System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "查找房间不存在：房间roomid=" + inJson.roomId);

			outJson.userId = inJson.userId;
			outJson.resultInfo = ResultInfoConstUtils.FINDROOM_ROOMNULLINFO;
			outJson.errorCode = ProtocalRegulation.ERRORCODE_NOROOM;
			outJson.result = false;
		} else {
			synchronized(roomInfo) {
				//当前人数如果大于等于房间总人数
				if (roomInfo.getActualParticipation() >= roomInfo.getParticipation()) {
					System.out.println("人满了");
					outJson.userId = inJson.userId;
					outJson.resultInfo = ResultInfoConstUtils.FINDROOM_ROOMFULLINFO;
					outJson.errorCode = ProtocalRegulation.ERRORCODE_ROOMFULL;
					outJson.result = false;
				} else {
					//获取自己的信息
					UserInfo mPlayer = userMap.get(inJson.userId).user;
					//此处不可能为空，因为在初始化处已经添加用户
					mPlayer.setCredits(0);
					String clientIP = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();//获取IP地址的正确途径
					mPlayer.setIp(clientIP);
					mPlayer.setRoomId(inJson.roomId);
					mPlayer.setPosition(roomInfo.getActualParticipation());//设置位置
					
					roomInfo.setActualParticipation(roomInfo.getActualParticipation() + 1);//参与人数加一
					
					UserSession mUserSession = new UserSession(mPlayer, session);
					roomInfo.getUserSessions().add(mUserSession);
					System.out.println("房间"+roomInfo.getRoomId()+"的参与人数 = " + roomInfo.getActualParticipation());
					
					
					notificationService.notificationJoinRoom(inJson.roomId, inJson.userId);//通知该房间的所有人
					return null;
				}
			}
			
		}
		res.setResultCode(ProtocalRegulation.FINDROOM);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}


}
